/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.codeview;


import ohos.agp.components.AttrSet;
import ohos.agp.components.webengine.JsCallback;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.ResourceResponse;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.utils.net.Uri;

import com.cv4j.uitl.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;


/**
 * CodeView
 *
 * @since 2021-05-18
 */
public class CodeView extends WebView {
    private static final String TAG = "CodeView";
    private static final String JS_NAME = "JsCallbackToApp";
    private String htmlCode;

    /**
     * CodeView
     *
     * @param context context
     */
    public CodeView(Context context) {
        this(context, null);
    }

    /**
     * CodeView
     *
     * @param context context
     * @param attrSet attrSet
     */
    public CodeView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        getWebConfig().setJavaScriptPermit(true);
        initData();
    }

    private void initData() {
        addJsCallback(JS_NAME, new JsCallback() {
            @Override
            public String onCallback(String msg) {
                // 增加自定义处理
                return htmlCode;
            }
        });

        setWebAgent(new WebAgent() {
            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                final String local = "/local/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getContext().getResourceManager()
                                .getRawFileEntry(rawFilePath).openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            Log.debug(TAG, "open raw file failed");
                        }
                    }
                    if (path.startsWith(local)) {
                        // 根据自定义规则访问本地文件
                        String localFile = getContext().getFilesDir() + path.replace(local, "/");
                        File file = new File(localFile);
                        if (!file.exists()) {
                            return super.processResourceRequest(webView, request);
                        }
                        String mimeType = URLConnection.guessContentTypeFromName(localFile);
                        InputStream inputStream = null;
                        try {
                            inputStream = new FileInputStream(file);
                            ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                            return response;
                        } catch (IOException e) {
                            Log.debug(TAG, "open local file failed");
                        } finally {
                            if (inputStream != null) {
                                try {
                                    inputStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        });
    }

    /**
     * showCode
     *
     * @param html html
     */
    public void showCode(String html) {
        htmlCode = html;
        load("https://example.com/rawfile/code_example.html");
    }
}
